package com.atguigu.exer;

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author yihu
 * @create 2021-06-03 16:48
 * @email:1057202547@qq.com
 * @dec: \
 * 练习3:获取文本上字符出现的次数,把数据写入文件
 *  *
 *  * 思路：
 *  * 1.遍历文本每一个字符
 *  * 2.字符出现的次数存在Map中
 *  *
 *  * Map<Character,Integer> map = new HashMap<Character,Integer>();
 *  * map.put('a',18);
 *  * map.put('你',2);
 *  *
 *  * 3.把map中的数据写入文件
 */
public class WordCout {

    @Test
    public void test1(){
        getWordCout(new File("hello1.tex"));
    }

    public void getWordCout(File srcFile){
        Map<Character, Integer> map = new HashMap<>();

        FileReader fr = null;
        BufferedWriter fw = null;
        try {
            fr = new FileReader(srcFile);
            int c = 0;
            while ((c = fr.read())!=-1){
                //int 还原 char
                char ch = (char) c;
                if(map.get(ch)==null){
                    map.put(ch,1);
                }else {
                    map.put(ch,map.get(ch) + 1);
                }
            }

            //将map 写入到一个文件中
            fw =new BufferedWriter(new FileWriter(srcFile.getName()+"wordcount.txt")) ;

            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Character, Integer> entry :entrySet){
                switch (entry.getKey()){
                    case ' ':
                        fw.write("空格=" + entry.getValue() );
                    case '\t'://\t表示tab 键字符
                        fw.write("tab键=" + entry.getValue() );
                        break;
                    case '\r'://
                        fw.write("回车=" + entry.getValue() );
                        break;
                    case '\n'://
                        fw.write("换行=" + entry.getValue());
                        break;
                    default:
                        fw.write(entry.getKey() +"="+ entry.getValue());
                        break;
                }
                fw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
